package io.noties.markwon.base.image.size

import android.graphics.Rect
import io.noties.markwon.base.image.AsyncDrawable
import timber.log.Timber

class ImageAutoSizePreLoadResolverDef(var maxWidth: Int, var textSize: Float) : ImageSizeResolverDef() {
    var autoResolved = false

    fun init(maxWidth: Int,   textSize: Float){
        Timber.d("ImageAutoSizeLoadResolverDef init maxWidth:${maxWidth} textSizw:${textSize}")
        this.maxWidth=maxWidth
        this.textSize=textSize
    }

    override fun resolveImageSize(drawable: AsyncDrawable): Rect {
        autoResolved = false
        val imageSize = drawable.imageSize?:return Rect(0,0,0,0)
        var rect = Rect(0,0,0,0)
        val width = imageSize.width
        val height = imageSize.height
        if (width != null) {
            var w: Int
            val h: Int
            var ratio = 1.0f
            if (UNIT_PERCENT == width.unit) {
                autoResolved = true
                w = (maxWidth * (width.value / 100f) + .5f).toInt()
            } else {
                w = resolveAbsolute(width, 0, textSize)
                if (w > maxWidth) {
                    ratio = maxWidth * 1f / w
                    w = maxWidth
                    autoResolved = true
                }
            }
            if (height != null) {
                h = if (UNIT_PERCENT == height.unit) {
                    (w * (height.value / 100f) + .5f).toInt()
                } else {
                    (resolveAbsolute(height, 0, textSize) * ratio).toInt()
                }
            } else {
                h = w / 2
                autoResolved = false
            }
            rect = Rect(0, 0, w, h)
        }
        return rect
    }
}